<template>

    <el-card class="search-card" shadow="never">
        <!-- 搜索部分 -->
        <el-row :gutter="10" class="search-section">
            <el-col :span="7">
                <el-form-item label="所属部门：">
                    <el-tree-select :data="options" :props="props" v-model="searchData.deptIdList" multiple filterable
                        clearable highlight-current style="width: 240px" @change="handleDepartmentChange" />
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="用户名称：">
                    <el-input v-model="searchData.username" placeholder="请输入用户名称"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="手机号码：">
                    <el-input v-model="searchData.phone" placeholder="请输入手机号码"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-form-item label="状态">
                    <el-select v-model="searchData.status" placeholder="请选择状态">
                        <el-option label="正常" value="1"></el-option>
                        <el-option label="停用" value="0"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>

        </el-row>
        <el-row :gutter="10" class="search-section2">
            <el-col :span="9">
                <el-form-item label="创建时间：">
                    <div class="block">
                        <el-date-picker v-model="searchData.createTimeList" type="daterange" unlink-panels
                            range-separator=">>" start-placeholder="开始日期" end-placeholder="结束日期"
                            :shortcuts="shortcuts" />
                    </div>

                </el-form-item>

            </el-col>
            <el-col :span="5">
                <el-button type="primary" class="action-button" @click="search" :icon="Search">搜索</el-button>
                <el-button @click="reset" type="primary" class="action-button" :icon="Refresh">重置</el-button>
            </el-col>
        </el-row>
    </el-card>
    <!-- 操作按钮组 -->
    <div class="button-group">
        <el-button class="action-button" type="primary" :icon="Edit" @click="handleAdd">增加</el-button>

        <el-button class="action-button" type="primary" :icon="Upload" @click="handleImport">导入</el-button>
        <input type="file" ref="fileInput" @change="handleFileUpload" style="display: none" accept=".xlsx,.xls,.csv" />
        <el-button class="action-button" type="primary" :icon="Download" @click="handleExport">导出</el-button>
        <el-button class="action-button" type="primary" :icon="Delete" :disabled="!hasSelected"
            @click="handleBatchDelete" plain>
            删除
        </el-button>
        <el-button class="action-button" type="primary" :disabled="!hasSelected" @click="handleBatchEnable" plain>
            启用
        </el-button>
        <el-button class="action-button" type="primary" :disabled="!hasSelected" @click="handleBatchDisable" plain>
            禁用
        </el-button>
    </div>

    <!-- 批量操作按钮区域 -->
    <div style="margin-bottom: 10px;margin-left: 10px;">

    </div>
    <!-- 数据表格 -->
    <el-table ref="tableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <!-- 多选框列 -->
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="username" label="用户名" width="140" />
        <el-table-column prop="nickname" label="昵称" width="140" />
        <el-table-column prop="gender" label="性别" width="100">
            <template #default="scope">
                {{ getGenderText(scope.row.gender) }}
            </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
                <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                    style="--el-switch-on-color: #6067eb; --el-switch-off-color: #dcdfe6"
                    @change="handleStatusChange(scope.row)">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="180" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="remark" label="备注" />
        <!-- 操作列 -->
        <el-table-column label="操作" width="180">
            <template #default="scope">
                <el-button type="primary" text @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="danger" text @click="handleRowDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
        <el-pagination class="pagination-fixed" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pagination.currentPage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next" :total="pagination.totalNum">

        </el-pagination>
    </div>

</template>
<script lang="ts" setup>
import { ref, computed, watch, toRaw } from 'vue'
import type { User, UserDTO } from '../../type/User';
import type { PaginationData } from '../../type/PaginationData';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus';
import { Delete, Edit, Search, Share, Upload, Download, Refresh } from '@element-plus/icons-vue'
import { getUserInfo, exportUserInfo, importUserInfo, searchUserInfo } from '../../api/userApi';
import { getTenantDeptDTO } from '../../api/DeptApi';
import type { TenantDeptDTO } from '../../type/Department'
import type { CascaderValue, CascaderOption, ElCascader } from 'element-plus';

// 表格数据
const tableData = ref<User>();
//查询数据
const searchData = ref({
    username: "",
    phone: "",
    status: "",
    createTimeList: [],
    deptIdList: []
});


//分页
const pagination = ref<PaginationData<User>>({
    currentPage: 1,
    pageSize: 2,
    totalNum: 10,
    isMore: 0,
    totalPage: 0,
    startIndex: 0,
    items: []
});
//当每页条数发生了变化，调用此函数
const handleSizeChange = (val: number) => {
    pagination.value.pageSize = val;
    refreshData();

};
//当前页码发生变化，调用此函数
const handleCurrentChange = (val: number) => {
    pagination.value.currentPage = val;
    refreshData();

};

// ---------------------
// 获取用户数据
const getUserData = async () => {

    const res = await getUserInfo(pagination.value?.currentPage, pagination.value?.pageSize);

    const data = res;

    // 更新表格数据
    tableData.value = data.items;

    // 更新分页信息
    pagination.value.currentPage = data.currentPage;
    pagination.value.pageSize = data.pageSize;
    pagination.value.totalNum = data.totalNum;
    pagination.value.isMore = data.isMore;
    pagination.value.totalPage = data.totalPage;
    pagination.value.startIndex = data.startIndex;

}
getUserData();
//刷新数据
const refreshData = async () => {
    getUserData();
    getDeptData();
}
//部门搜索
const props = {
    value: 'id',      // 默认值，可以根据需要自定义
    label: 'name',      // 默认标签，可以根据需要自定义
    children: 'children',// 默认子选项，可以根据需要自定义

}

const options = ref<TenantDeptDTO[]>()

//获取部门数据
const getDeptData = async () => {
    const res = await getTenantDeptDTO();
    options.value = res;
}
// 处理选中变化
const handleDepartmentChange = (value: string[]) => {
    console.log('选中的部门 ID：', searchData.value.deptIdList);

}

getDeptData();
// 获取性别的中文表示
const getGenderText = (gender: string): string => {
    switch (gender) {
        case "1":
            return '男';
        case "0":
            return '女';
        default:
            return '神秘';
    }
};
// 状态切换的处理函数
const handleStatusChange = (row: User) => {
    // 更新状态逻辑，可以调用 API 等
    ElMessage({
        message: `已将 ${row.username} 的状态更改为 ${row.status == "1" ? '正常' : '禁用'}`,
        type: 'success',
    });
};
//日期选择器
const size = ref<'default' | 'large' | 'small'>('default')
const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]


//------------搜索----------------
const search = async () => {

    const res = await searchUserInfo(pagination.value.totalPage, pagination.value.pageSize, searchData.value);

    // 更新表格数据
    tableData.value = res.items;

    // 更新分页信息
    pagination.value.currentPage = res.currentPage;
    pagination.value.pageSize = res.pageSize;
    pagination.value.totalNum = res.totalNum;
    pagination.value.isMore = res.isMore;
    pagination.value.totalPage = res.totalPage;
    pagination.value.startIndex = res.startIndex;
}
const reset = async () => {
    searchData.value.username = "";
    searchData.value.phone = "";
    searchData.value.status = "";
    searchData.value.createTimeList = [];
    searchData.value.deptIdList = [];
    refreshData();
}

// 处理顶部按钮操作
const handleAdd = async () => {
    console.log('增加按钮点击')
    // 在此添加增加操作的逻辑
}

const handleDelete = async () => {
    console.log('删除按钮点击')
    // 在此添加删除操作的逻辑
}
//----------导入部分--------
const fileInput = ref<HTMLInputElement | null>(null);

// 触发文件输入
function handleImport() {
    fileInput.value?.click();
}
const handleFileUpload = async (event: Event) => {
    console.log('导入按钮点击')
    // 在此添加导入操作的逻辑
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (file) {
        const formData = new FormData();
        formData.append('file', file);
        await importUserInfo(formData);

    }
}

const handleExport = async () => {
    console.log('导出按钮点击')
    // 在此添加导出操作的逻辑
    await exportUserInfo();
}
//----------------------------
// 编辑行的处理函数
const handleEdit = (index: number, row: User) => {
    // 编辑逻辑
    ElMessage({
        message: `编辑第 ${index + 1} 行: ${row.username}`,
        type: 'info',
    });
};

// 删除行的处理函数
const handleRowDelete = (index: number, row: User) => {
    ElMessageBox.confirm(`确定删除 ${row.username} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            //tableData.value.splice(index, 1);
            ElMessage.success('删除成功');
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
};

//------------------
// 管理选中行
const tableRef = ref<InstanceType<typeof import('element-plus')['ElTable']> | null>(null);
const selectedRows = ref<User[]>([]);

// 监听选中行变化
const handleSelectionChange = (selection: User[]) => {
    selectedRows.value = selection;
};

// 计算是否有选中行
const hasSelected = computed(() => selectedRows.value.length > 0);

// 批量删除处理函数
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) return;

    ElMessageBox.confirm(
        `确定删除选中的 ${selectedRows.value.length} 条数据吗?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            /* tableData.value = tableData.value.filter(
              (row) => !selectedRows.value.includes(row)
            ); */
            ElMessage.success('批量删除成功');
            // 清空选中
            selectedRows.value = [];
        })
        .catch(() => {
            ElMessage.info('已取消批量删除');
        });
};

// 批量启用处理函数
const handleBatchEnable = () => {
    if (selectedRows.value.length === 0) return;

    selectedRows.value.forEach((row) => {
        row.status = "1";
    });

    ElMessage({
        type: 'success',
        message: `已批量启用 ${selectedRows.value.length} 条数据`,
    });

    // 如果需要，可以调用 API 更新状态
};

// 批量禁用处理函数
const handleBatchDisable = () => {
    if (selectedRows.value.length === 0) return;

    selectedRows.value.forEach((row) => {
        row.status = "0";
    });

    ElMessage({
        type: 'success',
        message: `已批量禁用 ${selectedRows.value.length} 条数据`,
    });

    // 如果需要，可以调用 API 更新状态
};



</script>
<style lang="scss" scoped>
/* 变量定义 */
// $primary-color: #8f5dcc;
$primary-color: #6067eb;
$button-border-radius: 4px;
$button-padding: 0.5rem 1rem;
$button-font-size: 16px;
$color-hover: darken($primary-color, 10%); // 悬浮时的颜色
$color-disabled: lighten($primary-color, 15%); // 禁用时的颜色

/* 定义一个 mixin 用于公共按钮样式 */
@mixin action-button-style {
    border-radius: $button-border-radius;
    padding: $button-padding;
    font-size: $button-font-size;
    cursor: pointer;
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;

    /* 覆盖 Element Plus 的 primary 按钮样式 */
    &.el-button--primary {
        background-color: $primary-color;
        border-color: $primary-color;
        color: #fff;

        &:hover,
        &:focus {
            background-color: $color-hover;
            border-color: $color-hover;
            color: #fff;
        }

        &.is-disabled {
            background-color: $color-disabled;
            border-color: $color-disabled;
            color: #fff;
            cursor: not-allowed;
            opacity: 1; // 确保颜色不被 Element Plus 默认的透明度覆盖
        }
    }

    /* 禁用状态下的样式（针对所有类型的按钮） */
    &:disabled,
    &.is-disabled {
        background-color: $color-disabled;
        border-color: $color-disabled;
        color: #fff;
        cursor: not-allowed;
        opacity: 1; // 覆盖 Element Plus 默认的透明度
    }


}

.search-card {
    border-radius: 10px;

    .block {
        padding: 0px 0;
        text-align: center;
        border-right: solid 1px var(--el-border-color);
        flex: 1;
    }

    .block:last-child {
        border-right: none;
    }

    .action-button {
        @include action-button-style;
    }
}

/* 按钮组样式 */
.button-group {
    display: flex;
    gap: 1rem;
    margin: 1rem 0;

    .action-button {
        @include action-button-style;
    }
}

.pagination-container {
    display: flex;
    margin-top: 25px;
    justify-content: right;
    width: 100%;
    z-index: 1000;
}
</style>